package com.algorithm.ch1.cjm.linkedlist;

import com.algorithm.ch1.cjm.linkedlist.model.ListNode;

/**
 * 合并两个有序链表
 * 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * <p>
 * 示例：
 * <p>
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 */
public class MergeTwoLists {

    public static void main(String[] args) {

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;


        ListNode node10 = new ListNode(2);
        ListNode node20 = new ListNode(4);
        ListNode node30 = new ListNode(5);
        ListNode node40 = new ListNode(8);
//        ListNode node50 = new ListNode(9);
        node10.next = node20;
        node20.next = node30;
        node30.next = node40;
//        node40.next = node50;

        ListNode node =  mergeTwoLists(node1,node10);

        ListNode.print(node);
    }

    /**
     * 合并两个链表
     * T(n) = 2n;
     * f(n) = n;
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode pre = null;
        ListNode next1 = l1;
        ListNode next2 = l2;

        ListNode temp1 = null;
        ListNode temp2 = null;

        while (next1 != null || next2 != null){

            if(next1 != null && next2 != null && next1.val == next2.val){

                temp1 = new ListNode(next1.val);
                temp2 = new ListNode(next2.val);

                temp1.next = temp2;

                temp2.next = pre;

                pre = temp1;

                next1 = next1.next;
                next2 = next2.next;

            }else if(next1 == null || next2 != null && next1.val > next2.val){

                temp2 = new ListNode(next2.val);

                temp2.next = pre;

                pre = temp2;

                next2 = next2.next;
            }else if(next2 == null || next1 != null && next1.val < next2.val){

                temp1 = new ListNode(next1.val);

                temp1.next = pre;

                pre = temp1;

                next1 = next1.next;
            }
        }

        pre = reverseList(pre);

        return pre;
    }

    /**
     * 反转
     * @param head
     * @return
     */
    private static ListNode reverseList(ListNode head){

        ListNode pre = null;
        ListNode next = head;

        while (next != null){

            ListNode temp = next.next;

            next.next = pre;
            pre = next;

            next = temp;

        }

        return pre;
    }
}
